//
//  LoanRecordViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/12/25.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import SwiftyJSON

class LoanRecordViewController: KMViewController {
    
    fileprivate let cellId = "loanRecordCell"
    fileprivate var dataArray = [LoanRecordModel]()
    
    fileprivate var tableView : UITableView!
    
    init(title:String) {
        super.init(nibName: nil, bundle: nil)
        
        self.title = title
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        createTableView()
        getData()
    }
    
    //MARK: 创建tableView
    fileprivate func createTableView() {
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.backgroundColor = UIColor.clear
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(LoanRecordCell.self, forCellReuseIdentifier: cellId)
        self.view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
    }
    
    //MARK: 获取数据
    fileprivate func getData() {
        
        KMTool.requestMethod(.get, URLString: url_getLoanRecord, parameters: ["user_name":KMTool.stringForEnumKey(.phone) ?? ""], success: { (value, json) in
            
            if let dic = json["msg"].arrayObject as? [[String:Any]] {
                
                self.dataArray.removeAll()
                
                for item in dic {
                    let model = LoanRecordModel.setModel(with: item)
                    self.dataArray.append(model)
                }
                
                self.tableView.reloadData()
            }
            
        }) {
            
        }
    }

}

extension LoanRecordViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return RATIO_H(maxNum: 190)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? LoanRecordCell
        cell?.selectionStyle = .none
        cell?.delegate = self
        cell?.model = dataArray[indexPath.row]
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
    }
}

extension LoanRecordViewController : LoanRecordCellDelegate {
    
    //MARK: 修改贷款记录
    func changeLoanRecord(loanId: String, status: String) {
        
        KMTool.waiting()
        KMTool.requestGetData(URLString: url_changeLoanRecord, parameters: ["id":loanId,"status":status], success: { (data) in
            
            KMTool.stop()
            let string = NSString.init(data: data, encoding: String.Encoding.utf8.rawValue)
            if string == "1" {
                KMTool.showText(_text: changeSuccess)
                self.getData()
            }else{
                KMTool.showText(_text: changeFail)
            }
            
        }) {
            KMTool.stop()
        }
    }
    
    //MARK: 查看产品
    func productDetails(model: LoanRecordModel) {
        
        let loanRecordDetailsVC = LoanRecordDetailsViewController.init(model: model)
        loanRecordDetailsVC.modalPresentationStyle = .overCurrentContext
        loanRecordDetailsVC.view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        self.present(loanRecordDetailsVC, animated: false, completion: nil)
    }
    
    //MARK: 贷款记录详情
    func loanRecordDetails(model: LoanRecordModel) {
        
        let json = JSON.init(model.recommends ?? Any.self)
        if let recommends = json["list"].arrayObject as? [[String:Any]] {
            
            if recommends.count == 1 {
                let model = LoanRecordListModel.setModel(with: recommends.first!)
                let webVC = LoanDetailsWebViewController.init(urlStr: model.id!, title: "")
                webVC.removeElements = ["top-bar","footer"]
                self.navigationController?.pushViewController(webVC, animated: true)
            }else{
                
                var array = [LoanRecordListModel]()
                
                for item in recommends {
                    let model = LoanRecordListModel.setModel(with: item)
                    array.append(model)
                }
                
                let loanProductVC = LoanProductViewController.init(array: array)
                loanProductVC.modalPresentationStyle = .overCurrentContext
                loanProductVC.view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
                loanProductVC.loanDetailsBlock = { (loanId) in
                    let webVC = LoanDetailsWebViewController.init(urlStr: loanId, title: "")
                    webVC.removeElements = ["top-bar","footer"]
                    self.navigationController?.pushViewController(webVC, animated: true)
                }
                self.present(loanProductVC, animated: false, completion: nil)
            }
        
        }else{
            KMTool.showText(_text: notProduct)
        }
    }
}
